package com.cx.bank.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * 完成Hibernate工具类 封装配置文件读取操作 封装SessionFactory创建操作 封装session获得操作
 * 
 * @author Administrator
 */
public class HibernateUtils {
	
	private static SessionFactory sessionFactory;
	
	static {
		// 加载配置
		Configuration conf = new Configuration().configure();
		// 根据Configuration 配置创建SessionFactory
		sessionFactory = conf.buildSessionFactory();
		//当虚拟机关闭时释放资源
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			public void run() {
				sessionFactory.close();
			}
		}));
	}

	public static Session openSession() {

		// 从SessionFactory中得到session
		Session session = sessionFactory.openSession();
		return session;
	}

	public static Session getCurrentSession() {
		
		// 从SessionFactory中得到session
		Session session = sessionFactory.getCurrentSession();
		return session;
	}
	public static void closeSession(Session session) {
		if (session != null) {
			if (session.isOpen()) {
				session.close();
			}
		}
		System.out.println("session已关闭");
	}
	
}

